﻿
//sockettool  下载地址：
//https://gitcode.com/Premium-Resources/ba879/?utm_source=article_gitcode_universal&index=top&type=card&uuid_tt_dd=10_18644933070-1756311524498-176504&from_id=148161252&from_link=9b0954f021a6bb5168c0da799fc9c266

using System.Net;
using System.Net.Sockets;
using System.Text;

int port = 10086;
//1.创建监听端口对象,启动监听
TcpListener listener=new TcpListener(IPAddress.Any, port);
listener.Start();
string serverIP=listener.LocalEndpoint.ToString();
Console.WriteLine($"server({serverIP}) started!");
//2.监听连接的客户端，这里会等待
TcpClient client= await listener.AcceptTcpClientAsync();
string clientIP = client.Client.RemoteEndPoint.ToString();
Console.WriteLine($"client({clientIP}) connected!");
//3.using 用于自动释放资源
using (client)
//4.获取client 发来的数据
using(NetworkStream stream = client.GetStream())
{
    byte[] buffer= new byte[1024];
    int bytesRead;
    //5.读取客户端发来的消息
    while((bytesRead =await stream.ReadAsync(buffer,0,buffer.Length)) > 0)
    {
        //转换字节流成字符串
        string data=Encoding.ASCII.GetString(buffer,0,bytesRead);
        Console.WriteLine($"received : {data}");
        //6.发送响应消息给客户端
        string response = $"i received your data:{data}";
        byte[] msg= Encoding.ASCII.GetBytes(response);
        await stream.WriteAsync(msg,0,msg.Length);
        Console.WriteLine($"send: {response}");
    }
}

Console.WriteLine($"client({clientIP}) disconnected!");

listener.Stop();
Console.WriteLine($"server({serverIP}) stopped!");